package ai.mspbots.sql.repository;

import ai.mspbots.sql.ai.DeepSeekOperation;
import ai.mspbots.sql.datasource.DataSourceContextHolder;
import ai.mspbots.sql.dto.DdlDTO;
import ai.mspbots.sql.dto.QueryDTO;
import ai.mspbots.sql.entity.GenerateSql;
import ai.mspbots.sql.mapper.GenerateSqlMapper;
import ai.mspbots.sql.service.SQLParserService;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class SqlRepository {

    private final DeepSeekOperation deepSeekOperation;

    private final GenerateSqlMapper generateSqlMapper;

    private final SQLParserService sqlParserService;

    private final ThreadPoolTaskExecutor taskExecutor;

    public List<DdlDTO> generateSql(String sql) {
        List<QueryDTO> deepSeekResponse = deepSeekOperation.explainSql(sql);
        return deepSeekResponse.stream().map(queryDTO -> {
            String table = queryDTO.getTable();
            String query = queryDTO.getQuery();
            log.info("table: {}, query: {}", table, query);
            GenerateSql generateSql = generateSqlMapper.queryDdl(table);
            // String createTable = deepSeekOperation.formatSql(generateSql.toString());
            String assembled = sqlParserService.assemble(table, query, null, null);
            DdlDTO ddldto = new DdlDTO();
            ddldto.setDdl(generateSql.toString());
            ddldto.setData(assembled);
            return ddldto;
        }).collect(Collectors.toList());
    }

    public List<QueryDTO> explainSql(String sql) {
        List<QueryDTO> deepSeekResponse = deepSeekOperation.explainSql(sql);
//        deepSeekResponse.forEach(queryDTO -> {
//            String table = queryDTO.getTable();
//            String query = queryDTO.getQuery();
//            String count = queryDTO.getCount();
//            String dataSourceType = DynamicDataSourceContextHolder.peek();
//            taskExecutor.submit(() -> {
//                String date = DateUtil.date().toString(DatePattern.PURE_DATETIME_PATTERN);
//                try {
//                    DynamicDataSourceContextHolder.push(dataSourceType);
//                    sqlParserService.assemble(table, query, count, date);
//                } catch (Exception e) {
//                    // 处理异常
//                    System.err.println("Error processing table: " + table);
//                    System.err.println("Query: " + query);
//                    System.err.println("Count: " + count);
//                    System.err.println("Date: " + date);
//                    e.printStackTrace();
//                } finally {
//                    DynamicDataSourceContextHolder.clear();
//                }
//            });
//        });

        return deepSeekResponse;
    }
}
